package com.skymxc.wandroidtodo.page.main;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;

import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.skymxc.wandroidtodo.R;
import com.skymxc.wandroidtodo.adapter.TODOItemAdapter;
import com.skymxc.wandroidtodo.data.net.RetrofitManager;
import com.skymxc.wandroidtodo.databinding.ActivityMainBinding;
import com.skymxc.wandroidtodo.entity.PageResult;
import com.skymxc.wandroidtodo.entity.TODOItem;
import com.skymxc.wandroidtodo.page.add.AddItemActivity;
import com.skymxc.wandroidtodo.page.base.BaseActivity;
import com.skymxc.wandroidtodo.page.update.UpdateItemActivity;

import java.util.List;

public class MainActivity extends BaseActivity<MainPresenter>
        implements MainContact.MainView, OnRefreshListener,
        OnLoadMoreListener, TODOItemAdapter.ClickCallback {

    public static final int CODE_RESULT_ADD = 1;
    public static final int CODE_RESULT_UPDATE = 2;
    private ActivityMainBinding mBinding;


    @Override
    protected void initView() {
        super.initView();
        mBinding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(mBinding.getRoot());
        mBinding.mainRecycler.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        mBinding.mainRefresh.setOnRefreshListener(this);
        mBinding.mainRefresh.setOnLoadMoreListener(this);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        mBinding.mainRefresh.autoRefresh();
    }

    @Override
    protected MainPresenter initPresenter() {
        return new MainPresenter(getApplication());
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == R.id.menu_add) {
            Intent intent = new Intent(this, AddItemActivity.class);
            startActivityForResult(intent, CODE_RESULT_ADD);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case CODE_RESULT_ADD:
            case CODE_RESULT_UPDATE:
                if (resultCode == RESULT_OK) {
                    mBinding.mainRefresh.autoRefresh();
                }
                break;
        }
    }

    @Override
    public void loadPageSuccess(PageResult result) {
        List<TODOItem> todoItems = result.getDatas();
        //显示到屏幕上

        if (mBinding.mainRefresh.isRefreshing()) {
            mBinding.mainRefresh.finishRefresh(100);
            TODOItemAdapter adapter = new TODOItemAdapter(todoItems);
            adapter.setClickCallback(this);
            mBinding.mainRecycler.setAdapter(adapter);
        } else if (mBinding.mainRefresh.isLoading()) {
            mBinding.mainRefresh.finishLoadMore(100);
            RecyclerView.Adapter recyclerAdapter = mBinding.mainRecycler.getAdapter();
            TODOItemAdapter adapter = (TODOItemAdapter) recyclerAdapter;
            adapter.add(todoItems);
        }
        mBinding.mainRefresh.setEnableLoadMore(!result.isOver());


    }

    @Override
    public void updateItemStatusSuccess() {
        Log.i("MainActivity.java", "updateItemStatusSuccess: ");
        hideProgress();
    }

    @Override
    public void updateItemStatusFail() {
        showConfirm("修改失败");
        mBinding.mainRecycler.getAdapter().notifyDataSetChanged();
        hideProgress();
    }

    @Override
    public void deleteItemSuccess(TODOItem item) {
        //将其从 item 中删除
        hideProgress();
        RecyclerView.Adapter adapter = mBinding.mainRecycler.getAdapter();
        if (adapter instanceof TODOItemAdapter) {
            TODOItemAdapter itemAdapter = (TODOItemAdapter) adapter;
            itemAdapter.removeItem(item);
        }
    }

    @Override
    public void showError(String msg, int errCode) {
        super.showError(msg, errCode);
        if (mBinding.mainRefresh.isRefreshing()) {
            mBinding.mainRefresh.finishRefresh(false);
        } else if (mBinding.mainRefresh.isLoading()) {
            mBinding.mainRefresh.finishLoadMore(false);
        }
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        mPresenter.loadData();
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        mPresenter.refresh();
    }

    @Override
    public void onDeleteClick(TODOItem item) {
        showConfirm("确认删除吗？", true, true, new DialogListener() {
            @Override
            public void onConfirm() {
                mPresenter.deleteItem(item);
            }

            @Override
            public void onCancel() {

            }
        });
    }

    @Override
    public void onUpdateCLick(TODOItem item) {
        Intent intent = UpdateItemActivity.newIntent(this,item);
        startActivityForResult(intent,CODE_RESULT_UPDATE);
    }

    @Override
    public void onCheckChanged(TODOItem item, boolean isChecked) {
        mPresenter.updateItemStatus(item, isChecked);
    }
}